package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;


/**
 * 定时任务类
 */
@Component
@Slf4j
public class MyTask {

    @Autowired
    private OrderMapper orderMapper;


    /**
     * 定时任务方法  没有返回值
     */
//    @Scheduled(cron = "0/5 * * * * ?")
//    public void test1(){
//        log.info("启动了 {}",new Date());
//    }


    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeoutOrder(){
      Integer  status = Orders.PENDING_PAYMENT;
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList =  orderMapper.selectTimeoutByStatus(status,time);
        if (ordersList != null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付时间超时");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    @Scheduled(cron = "0 0 2 * * ? ")
    public void processDeliveryOrder(){
        LocalDateTime time = LocalDateTime.now().plusHours(-2);
        List<Orders> ordersList =  orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,time);
        if (ordersList != null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
